package cc.md888.app.utils;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtil {
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";

    // 加密方法
    public static String encrypt(String content, String key) {
        try {
            byte[] raw = key.getBytes();
            SecretKeySpec secretKey = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            byte[] encrypted = cipher.doFinal(byteContent);
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    // 解密方法
    public static String decrypt(String encrypted, String key) {
        try {
            byte[] raw = key.getBytes();
            SecretKeySpec secretKey = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] encryptedBytes = Base64.getDecoder().decode(encrypted);
            byte[] decrypted = cipher.doFinal(encryptedBytes);
            return new String(decrypted, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    public static void main(String[] args) throws Exception{
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        String key  = Hex.encodeHexString(secretKey.getEncoded());
        System.out.println(key);
        String uuid = encrypt("61580542388319", key);
        System.out.println(uuid);
//        System.out.println(encrypt("hello", key));
//        System.out.println(decrypt(encrypt("hello", key), key));
    }
}
